package com.tttare.haoyigou.solrutil;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tttare.haoyigou.mapper.TbItemMapper;
import com.tttare.haoyigou.pojo.TbItem;
import com.tttare.haoyigou.pojo.TbItemExample;
import com.tttare.haoyigou.pojo.TbItemExample.Criteria;


@Component
public class SolrUtil {

	@Autowired
	private TbItemMapper tbItemMapper;
	
	@Autowired
	private SolrTemplate solrTemplate;
	
	public void importItemData(){
		//先查出所有的item
		TbItemExample example = new TbItemExample();
		//只有过审的商品才能上架
		Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo("1");
		List<TbItem> list = tbItemMapper.selectByExample(example);
		//存入solr库
		for (TbItem item : list) {
			Map<String,String> map = JSON.parseObject(item.getSpec(),Map.class);
			item.setSpecMap(map);
			System.out.println(item.getId()+" "+item.getTitle());
		}
		//存入集合,就是批量保存
		solrTemplate.saveBeans(list);//批量保存时,一定是saveBeans,哇,搞了很久
		solrTemplate.commit();
	}
	
	public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("classpath*:spring/application*.xml");
		//classpath*:匹配所有classpath下的配置,包括jar包
		SolrUtil solrUtil = context.getBean(SolrUtil.class);
		//让spring创建bean,才能完成注入等操作,其实可以在其他类里面用@Test方法来调用import
		solrUtil.importItemData();
	}
}
